package com.ncmmall.api.security;

import com.feijin.commons.lang.PropertiesHelps;
import com.ncmmall.domain.business.merchant.MerchantGoodsChannel;
import com.ncmmall.domain.business.merchant.QMerchantGoodsChannel;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.security.auth.login.AccountNotFoundException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.BadRequestException;
import java.util.List;

/**
 * @author linxs
 *         权限校验工具
 */
@Component
public final class Securitys {


    @Autowired
    private QueryChannelService queryChannelService;

    public static QueryChannelService querychannelservice;

    @PostConstruct
    public void init() {
        Securitys.querychannelservice = queryChannelService;
    }

    private Securitys() {
    }

    /**
     * 清理敏感信息
     *
     * @param params
     * @return
     */
    public static WebUser cleanUser(WebUser params) {
        WebUser member = new WebUser();
        BeanUtils.copyProperties(params, member);
        member.setPassword("");
        member.setNickname(Strings.isNullOrEmpty(member.getNickname()) ? "匿名" : member.getNickname());

        if (!Strings.isNullOrEmpty(member.getAvatar())) {
            member.setAvatarName(member.getAvatar());
            member.setAvatar(PropertiesHelps.getValue("store.domain") + "/avatar/" + member.getAvatar());
        }

        if(!Strings.isNullOrEmpty(member.getCertificate())) {
            member.setCertificateName(member.getCertificate());
            member.setCertificate(PropertiesHelps.getValue("store.domain") + "/uploads/" + member.getCertificate());
        }

        if (null != member.getMerchantEnterpriseInfo()) {
            if (!Strings.isNullOrEmpty(member.getMerchantEnterpriseInfo().getBusinessLicensePhoto())) {
                member.getMerchantEnterpriseInfo().setBusinessLicensePhotoData(PropertiesHelps.getValue("store.domain") + "/uploads/" + member.getMerchantEnterpriseInfo().getBusinessLicensePhoto());
                member.getMerchantEnterpriseInfo().setBusinessLicensePhoto(member.getMerchantEnterpriseInfo().getBusinessLicensePhoto());
            }

            if (!Strings.isNullOrEmpty(member.getMerchantEnterpriseInfo().getLegalPersonIdCardPhoto())) {
                member.getMerchantEnterpriseInfo().setLegalPersonIdCardPhotoData(PropertiesHelps.getValue("store.domain") + "/uploads/" + member.getMerchantEnterpriseInfo().getLegalPersonIdCardPhoto());
                member.getMerchantEnterpriseInfo().setLegalPersonIdCardPhoto(member.getMerchantEnterpriseInfo().getLegalPersonIdCardPhoto());
            }

            if (!Strings.isNullOrEmpty(member.getMerchantEnterpriseInfo().getLegalPersonIdCardPhotoBack())) {
                member.getMerchantEnterpriseInfo().setLegalPersonIdCardPhotoBackData(PropertiesHelps.getValue("store.domain") + "/uploads/" + member.getMerchantEnterpriseInfo().getLegalPersonIdCardPhotoBack());
                member.getMerchantEnterpriseInfo().setLegalPersonIdCardPhotoBack(member.getMerchantEnterpriseInfo().getLegalPersonIdCardPhotoBack());
            }

        }

        if (null != member.getMerchantIndividualInfo()) {

            if (!Strings.isNullOrEmpty(member.getMerchantIndividualInfo().getBusinessLicensePhoto())) {
                member.getMerchantIndividualInfo().setBusinessLicensePhotoData(PropertiesHelps.getValue("store.domain") + "/uploads/" + member.getMerchantIndividualInfo().getBusinessLicensePhoto());
                member.getMerchantIndividualInfo().setBusinessLicensePhoto(member.getMerchantIndividualInfo().getBusinessLicensePhoto());
            }

            if (!Strings.isNullOrEmpty(member.getMerchantIndividualInfo().getIdCardPhoto())) {
                member.getMerchantIndividualInfo().setIdCardPhotoData(PropertiesHelps.getValue("store.domain") + "/uploads/" + member.getMerchantIndividualInfo().getIdCardPhoto());
                member.getMerchantIndividualInfo().setIdCardPhoto(member.getMerchantIndividualInfo().getIdCardPhoto());
            }

            if (!Strings.isNullOrEmpty(member.getMerchantIndividualInfo().getIdCardPhotoBack())) {
                member.getMerchantIndividualInfo().setIdCardPhotoBackData(PropertiesHelps.getValue("store.domain") + "/uploads/" + member.getMerchantIndividualInfo().getIdCardPhotoBack());
                member.getMerchantIndividualInfo().setIdCardPhotoBack(member.getMerchantIndividualInfo().getIdCardPhotoBack());
            }
        }

        if (null != member.getMerchantPersonalInfo()) {

            if (!Strings.isNullOrEmpty(member.getMerchantPersonalInfo().getLegalPersonIdCardPhoto())) {
                member.getMerchantPersonalInfo().setLegalPersonIdCardPhotoData(PropertiesHelps.getValue("store.domain") + "/uploads/" + member.getMerchantPersonalInfo().getLegalPersonIdCardPhoto());
                member.getMerchantPersonalInfo().setLegalPersonIdCardPhoto(member.getMerchantPersonalInfo().getLegalPersonIdCardPhoto());
            }

            if (!Strings.isNullOrEmpty(member.getMerchantPersonalInfo().getLegalPersonIdCardPhotoBack())) {
                member.getMerchantPersonalInfo().setLegalPersonIdCardPhotoBackData(PropertiesHelps.getValue("store.domain") + "/uploads/" + member.getMerchantPersonalInfo().getLegalPersonIdCardPhotoBack());
                member.getMerchantPersonalInfo().setLegalPersonIdCardPhotoBack(member.getMerchantPersonalInfo().getLegalPersonIdCardPhotoBack());
            }
        }

        List<MerchantGoodsChannel> channels = querychannelservice.findAll(QMerchantGoodsChannel.merchantGoodsChannel.merchant.eq(member), MerchantGoodsChannel.class);
        List<String> ids = Lists.newArrayList();
        for (MerchantGoodsChannel channel : channels) {
            ids.add(String.valueOf(channel.getChannel().getId()));
        }

        member.setMerchantGoodsChannelsData(Joiner.on("-").join(ids));

        return member;
    }

    /**
     * 校验是否已登录
     */
    public static boolean isLogin(HttpServletRequest request) {
        if (Strings.isNullOrEmpty(request.getHeader("Authorization"))) {
            return false;
        }

        WebUser user = querychannelservice.queryOneEntity("select u.* from security_web_user u where u.accessToken = :token ", ImmutableMap.of("token", request.getHeader("Authorization")), WebUser.class);

        return null != user;
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     * @throws AccountNotFoundException
     */
    public static WebUser user(HttpServletRequest request) throws AccountNotFoundException {

        if (Strings.isNullOrEmpty(request.getHeader("Authorization"))) {
            throw new BadRequestException("[TOKEN为空]");
        }

        WebUser user = querychannelservice.findOne(QWebUser.webUser.accessToken.eq(request.getHeader("Authorization")), WebUser.class);

        if (null == user) {
            throw new AccountNotFoundException("[用户未登录或登录信息已过期]");
        }

        return user;
    }

    /**
     * 获取访问源IP地址
     *
     * @param request
     * @return
     */
    public static String ipAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.replaceAll(", 127.0.0.1", "");
    }

    /**
     * 获取请求头token
     *
     * @param request
     * @return
     */
    public static String token(HttpServletRequest request) {
        return request.getHeader("Authorization");
    }

}
